<template>
  <el-container class="level-edit">
    <el-main>
      <div class="tip"> 新增或编辑等级后，请及时在分销商品中完善对应的佣金规则 </div>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="150px">
        <div class="title">等级佣金比例</div>
        <el-form-item label="等级权重" prop="level">
          <div
            :class="[
              'item',
              ll.level == form.model.level ? 'is-active' : '',
              level.existLevel.includes(ll.level) ? 'is-disabled' : '',
              form.model.level == 1 ? 'is-none' : '',
            ]"
            v-for="ll in level.data"
            :key="ll"
            @click="onSelectLevel(ll.level)"
          >
            {{ ll.name }}
          </div>
        </el-form-item>
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="form.model.name" placeholder="请输入等级名称"></el-input>
        </el-form-item>
        <el-form-item label="等级徽章" prop="image">
          <sa-uploader v-model="form.model.image" fileType="image"></sa-uploader>
        </el-form-item>
        <el-form-item
          label="一级(自购)佣金比例"
          prop="commission_rules.commission_1"
          :rules="form.rules.commission_rules.commission"
        >
          <el-input
            class="sa-w-160"
            v-model="form.model.commission_rules.commission_1"
            type="number"
          >
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="二级佣金比例"
          prop="commission_rules.commission_2"
          :rules="form.rules.commission_rules.commission"
        >
          <el-input
            class="sa-w-160"
            v-model="form.model.commission_rules.commission_2"
            type="number"
          >
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="三级佣金比例"
          prop="commission_rules.commission_3"
          :rules="form.rules.commission_rules.commission"
        >
          <el-input
            class="sa-w-160"
            v-model="form.model.commission_rules.commission_3"
            type="number"
          >
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <template v-if="form.model.level != 1">
          <div class="title">添加升级条件</div>
          <el-form-item label="升级方式" prop="upgrade_rules">
            <div>
              <el-radio-group class="sa-m-b-8" v-model="form.model.upgrade_type">
                <el-radio :label="0">满足以下任意条件</el-radio>
                <el-radio :label="1">满足以下全部条件</el-radio>
              </el-radio-group>
              <div>
                <div
                  class="sa-flex sa-flex-wrap condition-group"
                  v-for="group in upgradeCondition"
                  :key="group"
                >
                  <div
                    :class="[
                      'item',
                      'condition-item',
                      Object.keys(form.model.upgrade_rules).includes(key) ? 'is-active' : '',
                    ]"
                    v-for="(item, key) in group"
                    :key="item"
                    @click="onSelectUpgrade(key)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          <template v-for="(group, gkey) in upgradeCondition" :key="group">
            <template v-for="(item, key) in group" :key="item">
              <el-form-item
                :label="item.name"
                v-if="Object.keys(form.model.upgrade_rules).includes(key)"
                :prop="`upgrade_rules.${key}`"
                :rules="form.rules.upgrade_rules_inner.rules"
              >
                <template v-if="gkey != 'agent_level'">
                  <el-input class="sa-w-124" v-model="form.model.upgrade_rules[key]" type="number">
                    <template #append> {{ initUnit(key) }}</template>
                  </el-input>
                  <el-button class="is-link sa-m-l-12" type="danger" @click="onDeleteRules(key)">
                    删除
                  </el-button>
                </template>
                <div v-if="gkey == 'agent_level'">
                  <div
                    class="sa-flex sa-flex-wrap sa-m-b-18"
                    v-for="(al, index) in form.model.upgrade_rules[key]"
                    :key="al"
                  >
                    <el-form-item
                      :prop="`upgrade_rules.${key}.${index}.level`"
                      :rules="form.rules.upgrade_rules_inner.level"
                    >
                      <el-select class="sa-w-160" v-model="al.level" placeholder="请选择分销商等级">
                        <template v-for="item in level.exist" :key="item">
                          <el-option
                            v-if="item.level < form.model.level"
                            :label="item.name"
                            :value="item.level"
                          />
                        </template>
                      </el-select>
                      <span class="sa-m-l-16 sa-m-r-12">满</span>
                    </el-form-item>
                    <el-form-item
                      :prop="`upgrade_rules.${key}.${index}.count`"
                      :rules="form.rules.upgrade_rules_inner.rules"
                    >
                      <el-input class="sa-w-120" v-model="al.count" type="number">
                        <template #append>人</template>
                      </el-input>
                      <el-button
                        class="is-link sa-m-l-12"
                        type="danger"
                        @click="onDeleteRules(key, index)"
                      >
                        删除
                      </el-button>
                    </el-form-item>
                  </div>
                  <el-button class="is-link" type="primary" size="small" @click="onAddRules(key)"
                    >+ 添加</el-button
                  >
                </div>
              </el-form-item>
            </template>
          </template>
        </template>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.commission.level.add'"
        type="primary"
        @click="confirm"
        >保存
      </el-button>
      <el-button
        v-if="modal.params.type == 'edit'"
        v-auth="'shop.admin.commission.level.edit'"
        type="primary"
        @click="confirm"
        >更新
      </el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { isObject } from '@/sheep/utils';
  import { api } from '../commission.service';
  import { cloneDeep, isEmpty } from 'lodash';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps(['modal']);

  const formRef = ref();
  const form = reactive({
    model: {
      level: null,
      name: '',
      image: '',
      commission_rules: {
        commission_1: '0.00',
        commission_2: '0.00',
        commission_3: '0.00',
      },
      upgrade_type: 0,
      upgrade_rules: {},
    },
    rules: {
      level: [{ required: true, message: '请选择等级权重', trigger: 'blur' }],
      name: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
      commission_rules: {
        commission: [{ required: true, message: '佣金比例', trigger: 'blur' }],
      },
      upgrade_rules: [
        {
          validator: (rule, value, callback) => {
            if (isEmpty(value)) {
              callback(new Error('请填写升级条件'));
            } else {
              callback();
            }
          },
          trigger: 'blur',
        },
      ],
      upgrade_rules_inner: {
        rules: [{ required: true, message: '请输入', trigger: 'blur' }],
        level: [{ required: true, message: '请选择分销商等级', trigger: 'blur' }],
      },
    },
  });

  async function getDetail() {
    const { error, data } = await api.level.detail(props.modal.params.id);
    if (error === 0) {
      form.model = data;
      if (!isObject(form.model.upgrade_rules)) form.model.upgrade_rules = {};

      // level=1时 等级权重不可修改
      if (data.level == 1) {
        level.data = [
          {
            name: '一级',
            level: 1,
          },
        ];

        level.existLevel = [];
        level.data.forEach((e) => {
          level.existLevel.push(e.level);
        });
      } else {
        level.data = cloneDeep(defaultLevel);
      }

      let index = level.existLevel.findIndex((l) => l == data.level);
      level.existLevel.splice(index, 1);
    }
  }

  function onSelectLevel(l) {
    if (!level.existLevel.includes(l)) {
      form.model.level = l;
      // 清空规则
      form.model.upgrade_rules = {};
    }
  }

  const defaultLevel = [
    {
      name: '一级',
      level: 1,
    },
    {
      name: '二级',
      level: 2,
    },
    {
      name: '三级',
      level: 3,
    },
    {
      name: '四级',
      level: 4,
    },
    {
      name: '五级',
      level: 5,
    },
    {
      name: '六级',
      level: 6,
    },
    {
      name: '七级',
      level: 7,
    },
    {
      name: '八级',
      level: 8,
    },
    {
      name: '九级',
      level: 9,
    },
    {
      name: '十级',
      level: 10,
    },
  ];

  const level = reactive({
    data: [],
    exist: [],
    existLevel: [],
  });
  async function getSelect() {
    const { data } = await api.level.select();
    level.exist = data;
    data.forEach((e) => {
      level.existLevel.push(e.level);
    });
  }

  const upgradeCondition = {
    user: {
      total_consume: {
        name: '用户消费金额',
      },
      child_user_count_1: {
        name: '一级用户人数',
      },
      child_user_count_2: {
        name: '二级用户人数',
      },
      child_user_count_all: {
        name: '团队用户人数',
      },
    },
    order_money: {
      child_order_money_0: {
        name: '自购分销订单总金额',
      },
      child_order_money_1: {
        name: '一级分销订单金额',
      },
      child_order_money_2: {
        name: '二级分销订单金额',
      },
      child_order_money_all: {
        name: '团队分销订单金额',
      },
    },
    order_count: {
      child_order_count_0: {
        name: '自购分销订单数量',
      },
      child_order_count_1: {
        name: '一级分销订单数量',
      },
      child_order_count_2: {
        name: '二级分销订单数量',
      },
      child_order_count_all: {
        name: '团队分销订单数量',
      },
    },
    agent_count: {
      child_agent_count_1: {
        name: '一级分销商人数',
      },
      child_agent_count_2: {
        name: '二级分销商人数',
      },
      child_agent_count_all: {
        name: '团队分销商人数',
      },
    },
    agent_level: {
      child_agent_level_all: {
        name: '团队分销商等级统计',
      },
      child_agent_level_1: {
        name: '一级分销商等级统计',
      },
    },
  };

  function onSelectUpgrade(key) {
    form.model.upgrade_rules[key] = '';
    if (key == 'child_agent_level_all' || key == 'child_agent_level_1') {
      form.model.upgrade_rules[key] = [
        {
          level: '',
          count: '',
        },
      ];
    }
  }

  function onAddRules(key) {
    form.model.upgrade_rules[key].push({
      level: '',
      count: '',
    });
  }
  function onDeleteRules(key, index) {
    if (key == 'child_agent_level_all' || key == 'child_agent_level_1') {
      form.model.upgrade_rules[key].splice(index, 1);
      if (form.model.upgrade_rules[key].length == 0) delete form.model.upgrade_rules[key];
    } else {
      delete form.model.upgrade_rules[key];
    }
  }

  function initUnit(key) {
    if (key.includes('child_user_count') || key.includes('child_agent_count')) {
      return '人';
    }
    if (key.includes('total_consume') || key.includes('child_order_money')) {
      return '元';
    }
    if (key.includes('child_order_count')) {
      return '单';
    }
  }

  function confirm() {
    unref(formRef) &&
      unref(formRef).validate(async (valid) => {
        if (valid) {
          const { error } =
            props.modal.params.type == 'add'
              ? await api.level.add(form.model)
              : await api.level.edit(props.modal.params.id, form.model);
          if (error == 0) emit('modalCallBack', { event: 'confirm' });
        }
      });
  }

  onMounted(async () => {
    await getSelect();
    if (props.modal.params.type == 'add') level.data = cloneDeep(defaultLevel);
    if (props.modal.params.type == 'edit') getDetail();
  });
</script>
<style lang="scss" scoped>
  .level-edit {
    .tip {
      padding: 15px 16px;
      line-height: 18px;
      font-size: 14px;
      font-weight: 500;
      color: var(--sa-font);
      border-radius: 4px;
      background: var(--sa-table-header-bg);
      margin-bottom: var(--sa-padding);
    }
    .title {
      background: var(--sa-background-hex-hover);
      height: 32px;
      line-height: 32px;
      padding: 0 16px;
      font-size: 12px;
      font-weight: 400;
      color: var(--sa-subtitle);
      margin: 0 0 16px;
      border-radius: 4px;
    }
    .item {
      height: 32px;
      padding: 0 16px;
      font-size: 14px;
      border: 1px solid var(--sa-border);
      border-radius: 4px;
      margin: 0 16px 16px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      &:last-of-type {
        margin: 0 0 16px 0;
      }
      &.is-disabled {
        background: var(--sa-background-hex-active);
        color: #fff;
        border: 1px solid var(--sa-background-hex-active);
        cursor: not-allowed;
      }
      &.is-active {
        background: var(--el-color-primary);
        color: #fff;
        border: 1px solid var(--el-color-primary);
        &.is-none {
          display: flex;
        }
      }
      &.is-none {
        display: none;
      }
    }
    .condition-group {
      .condition-item {
        padding: 0 12px;
      }
    }
  }
</style>
